<?php
/**
 * @author ZhouFei
 *
 */
class MysqlUtil
{
	private $link;
	
	private $select;

	private $query;

	private $rowData;

	private static $instance;

	public function __construct($host, $database, $user, $pass) {
		$this->connect($host, $database, $user, $pass);
	}

	public function __destruct() {
		$this->close();
	}

	public static function getInstance($host='', $database='', $user='', $pass='') {
		if (self::$instance == null) {
			self::$instance = new MysqlUtil($host, $database, $user, $pass);
		}
		return self::$instance;
	}
	
	public function connect($host, $database, $user, $pass) {
		$this->link = mysql_connect($host, $user, $pass) or die('Could not connect: ' . mysql_error()); 
		mysql_select_db($database, $this->link) or die('Could not select database');
		$this->exec(sprintf("SET NAMES '%s'", 'utf8'));
		return $this;
	}

	public function exec($sql, $parameters=array(), $debug=false) {
		$sql = str_replace("%%prefix%%", CFG_DB_TABLEPRE, $sql);
		$search = array();
		$replace = array();
		foreach($parameters as $key => $value) {
			$search[] = "%%$key%%";
			$replace[] = self::escape($value);
		}
		$sql = str_replace($search, $replace, $sql);
		if ($debug) { echo $sql; }
		$this->query = mysql_query($sql, $this->link) or exit('Invalid query: ' . mysql_error() . " " . $sql);
		return $this;
	}

	public function insert($table, $data, $action = 'insert', $parameters = '', $debug=false) {
		reset($data);
        $space = $query_1 = $query_2='';
		foreach ($data as $key => $val) {
			$query_1 .= $space . '`' . $key . '`';
			$query_2 .= $space . '\'' . self::escape($val) . '\'';
			$space = ', ';
		}
		$sql = 'insert into ' . $table . ' ('.$query_1.') values ('.$query_2.')';
		$this->query = $this->exec($sql, null, $debug);
		return $this->query;
    }

	public function update($table, $data, $parameters = '', $debug=false) {
		reset($data);
        $sql = 'update ' . $table . ' set ';
		$space = '';
		foreach ($data as $key => $val){
			$query .= $space .'`' . $key . '`' . '= \'' . self::escape($val). '\''; 
			$space=', ';
		}
		$sql .= $query . ' where ' . $parameters.' ';
		$this->query = $this->exec($sql, null, $debug);
		return $this->query;
    }	
	
	public function getQuery() {
		return $this->query;
	}

	public function getNext($type = MYSQL_ASSOC) {
		$this->rowData = mysql_fetch_array($this->getQuery(), $type);
		return $this->rowData;
	}

	public function getRow() {
		return $this->rowData;
	}

	public function getFirst($sql, $p=array(), $debug=false) {
		$this->exec($sql, $p, $debug)->getNext();
		$row  = $this->getRow();
		return $row ? $row : null;
	}

	public function getScalar($sql, $p=array(), $debug=false) {
		$this->exec($sql, $p, $debug)->getNext(MYSQL_NUM);
		return $this->getRow() ? $this->rowData[0] : null;
	}

	public function getAll($sql, $p=array(), $debug=false) {
		$this->exec($sql, $p, $debug);
		$a = array();
		while ($this->getNext()) {
			$a[] = $this->getRow();
		}
		return $a;
	}

	public function getAllLimit($sql, $limit=20, $offset=0) {
		$this->exec(sprintf("%s limit %s,%s", $sql, $limit, $offset));
		$a = array();
		while ($this->getNext()) {
			$a[] = $this-getDataRow();
		}
		return $a;
	}

	public function getInsertId() {
		return mysql_insert_id($this->link);
	}

	public function getRows() {
		return mysql_num_rows($this->getQuery());
	}

	public function close() {
		mysql_close($this->link);
	}

	public static function escape($string) {
		if(get_magic_quotes_gpc()) {
            $string = stripslashes($string);
        }
		return mysql_real_escape_string($string);
	}
}
?>